<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2023/8/30
 * Time: 21:25
 */

namespace app\reception\logic;

use app\common\model\Novel;
use app\common\model\NovelChapter;
use app\common\model\NovelCustom;
use app\reception\server\ContentServer;
use think\Db;
use think\db\exception\ModelNotFoundException;

class NovelLogic
{
    /**
     * 书籍信息
     * @param $novelId
     * @return \think\response\Json
     * @Author: whh
     */
    public function getNovelInfo($novelId)
    {
        $cache = 600;
        $filed = "id novel_id,cover,origin_title novel_title,author,freq_id,class_id,son_class_id,update_status,brief,number_words,chapter_up_time,popularity";
        try {
            $novel = \app\common\model\Novel::field($filed)
                ->where('id', $novelId)
                ->with(['freq', 'novel_class', 'novel_class_son'])
                ->cache($cache)
                ->findOrFail();
        } catch (ModelNotFoundException $e) {
            return errJson('小说不存在');
        }
        $novel['number_words_text'] = $novel->number_words_text;
        $novel['cover'] = $novel->cover_text;
        $maxChapter = NovelChapter::where('novel_id', $novelId)->field("chapter_no,name")->cache($cache)->order("chapter_no desc")->find();
        if ($maxChapter) {
            $novel['max_chapter'] = $maxChapter;
        }
        $novel->setInc('popularity');
        return sucJson($novel);
    }

    /**
     * 章节列表
     * @param $user
     * @param $novelId
     * @param $page
     * @param $limit
     * @param string $order
     * @return \think\response\Json
     */
    public function getNovelChapters($user, $novelId, $page, $limit, $order = 'asc')
    {
        $filed = "chapter_no,name,novel_id,is_pay,words,create_time";
        $list = NovelChapter::field($filed)->where('novel_id', $novelId)->page($page, $limit)->order("chapter_no " . $order)->select()->toArray();
        $novel = Novel::get($novelId);
        $words_fee = NovelLogic::getNovelWordsFee($user, $novel);
        foreach ($list as $k => $v) {
            $list[$k]['is_paid'] = 0;
            $list[$k]['price'] = 0;

            $checkResult = checkReadVoucher($user->id, $novelId, $v['chapter_no']);

            if ($checkResult) {
                $list[$k]['is_paid'] = 1;
            }
            if ($v['is_pay'] == 1 && $list[$k]['is_paid'] == 0){
                $multiple = sprintf("%.1f", $v['words'] / 1000);
                $list[$k]['price'] = intval($multiple * $words_fee);
            }
        }
        $count = NovelChapter::where('novel_id', $novelId)->count();
        return sucJson($list, $count);
    }


    /**
     * 小说收费方式
     * @param $user
     * @param $novel
     * @return array
     */
    public static function getNovelChargeWay($user, $novel)
    {
        $novel_id = $novel->id;
        $words_fee = null;//千字价格
        $first_pay = null;//开始收费章节
        $customWhere[] = ['manager_id', '=', $user->channel_id];
        $customWhere[] = ['novel_id', '=', $novel_id];
        $channelCustom = NovelCustom::where($customWhere)->find();
        if ($channelCustom) {
            $words_fee = $channelCustom->chapter_words_fee;
            $first_pay = $channelCustom->chapter_first_pay;
        }
        if ($words_fee === null || $first_pay === null) {
            $customWhere = [];
            $customWhere[] = ['manager_id', '=', $user->agent_id];
            $customWhere[] = ['novel_id', '=', $novel_id];
            $agentCustom = NovelCustom::where($customWhere)->find();
            if ($agentCustom) {
                if ($words_fee === null) {
                    $words_fee = $agentCustom->chapter_words_fee;
                }
                if ($first_pay === null) {
                    $first_pay = $agentCustom->chapter_first_pay;
                }
            }
        }
        if ($words_fee === null) {
            $words_fee = $novel->words_fee;
        }
        return [
            'words_fee' => $words_fee,
            'first_pay' => $first_pay
        ];
    }

    /**
     * 千字收费价格
     * @param $user
     * @param $novel
     * @return mixed
     * @throws ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getNovelWordsFee($user, $novel)
    {
        $words_fee = $novel->words_fee;
        if ($user->link_id){
            $link = Db::table("quick_link")->where("id", $user->link_id)->field("id,chapter_words_fee")->find();
            if ($link){
                $words_fee = $link['chapter_words_fee'];
            }
        }
        return $words_fee;
    }


    /**
     * 小说列表
     * @param $user
     * @param $where
     * @param $page
     * @param $limit
     * @param $orderBy
     * @return \think\response\Json
     */
    public function getNovels($user, $where, $page, $limit, $orderBy)
    {
        $cache = false;
        $filed = "id novel_id,cover,origin_title novel_title,author,number_words,freq_id,class_id,son_class_id,update_status,chapter_up_time,brief";

        $count = Novel::where($where)->count();

        $novels = Novel::where($where)->field($filed)
            ->order($orderBy)
            ->page($page, $limit)
            ->cache($cache)
            ->select();
        foreach ($novels as $k => $novel) {
            $novels[$k]['number_words_text'] = $novel->number_words_text;
        }
        $novels = $novels->toArray();
        $cidArr = array_column($novels, 'class_id');
        $fidArr = array_column($novels, 'freq_id');
        $sidArr = array_column($novels, 'son_class_id');

        $classList = ContentServer::plGetNovelClass($cidArr);
        $freqList = ContentServer::plGetNovelFreq($fidArr);
        $sonClassList = ContentServer::plGetNovelClassSon($sidArr);

        foreach ($novels as $k => $v) {
            $novels[$k]['cover'] = config('img_domain') . $v['cover'];
            $novels[$k]['freq'] = isset($freqList[$v['freq_id']]) ? $freqList[$v['freq_id']] : '';
            $novels[$k]['novel_class'] = isset($classList[$v['class_id']]) ? $classList[$v['class_id']] : '';
            $novels[$k]['novel_class_son'] = isset($sonClassList[$v['son_class_id']]) ? $sonClassList[$v['son_class_id']] : '';
        }

        return sucJson($novels, $count);
    }
}